<?php

require_once dirname(__FILE__).'/../lib/vehicleGeneratorConfiguration.class.php';
require_once dirname(__FILE__).'/../lib/vehicleGeneratorHelper.class.php';

/**
 * vehicle actions.
 *
 * @package    MVM Vehicle Showroom (r)
 * @subpackage vehicle
 * @author     Bo Wang < beau32 [at] gmail.com >
 * @version    SVN: $Id: actions.class.php 23810 2009-11-12 11:07:44Z Kris.Wallsmith $
 */
class vehicleActions extends autoVehicleActions {

  protected function processForm(sfWebRequest $request, sfForm $form) {
    $form->bind($request->getParameter($form->getName()), $request->getFiles($form->getName()));
    if ($form->isValid()) {
      $notice = $form->getObject()->isNew() ? 'The item was created successfully.' : 'The item was updated successfully.';

      try {
        $vehicle = $form->save();

        for($i=1; $i <= sfConfig::get('app_number_image_allowed'); $i++) {
          $path = $this->form->getValue('picture_'.$i);
          $vehiclePicture = $vehicle->getPicture($i);
          if($vehiclePicture && empty($path)) {
            $vehiclePicture->delete();
            continue;
          }
          if(!$vehiclePicture && empty($path)) {
            continue;
          }
          if(!$vehiclePicture && !empty($path)) {
            $vehiclePicture = new Picture();
          }
          $vehiclePicture->setVehicleId($vehicle->getId());
          $vehiclePicture->setFilename($path);
          $vehiclePicture->save();
        }
        sfContext::getInstance()->getConfiguration()->loadHelpers(array("I18N"));
        $message = __('Your vehicle details have been saved');
        $this->getUser()->setFlash('notice', $message);
      } catch (Doctrine_Validator_Exception $e) {

        $errorStack = $form->getObject()->getErrorStack();

        $message = get_class($form->getObject()) . ' has ' . count($errorStack) . " field" . (count($errorStack) > 1 ?  's' : null) . " with validation errors: ";
        foreach ($errorStack as $field => $errors) {
          $message .= "$field (" . implode(", ", $errors) . "), ";
        }
        $message = trim($message, ', ');

        $this->getUser()->setFlash('error', $message);
        return sfView::SUCCESS;
      }

      $this->dispatcher->notify(new sfEvent($this, 'admin.save_object', array('object' => $vehicle)));

      if ($request->hasParameter('_save_and_add')) {
        $this->getUser()->setFlash('notice', $notice.' You can add another one below.');

        $this->redirect('@vehicle_new');
      }
      else {
        $this->getUser()->setFlash('notice', $notice);

        $this->redirect(array('sf_route' => 'vehicle_edit', 'sf_subject' => $vehicle));
      }
    }
    else {
      $this->getUser()->setFlash('error', 'The item has not been saved due to some errors.', false);
    }

  }
  public function executeUpdatemodel(sfWebRequest $request) {

    $make = MakeTable::getInstance()->find($request->getParameter('id'));

    $this->models= $make->getModels();

  }
  public function executeEdit(sfWebRequest $request) {

    $this->vehicle = $this->getRoute()->getObject();
    $this->form = $this->configuration->getForm($this->vehicle);
    $this->setTemplate('edit');
    if($request->isMethod('post')) {
      $this->processForm($request, $this->form);
    }
  }
  public function executeUploadPhoto(sfWebRequest $request) {
    try {
      $uploadDir = sfConfig::get('app_image_path');
      $fullUploadDir = sfConfig::get('sf_web_dir').$uploadDir;


      $fileDetails = $request->getFiles('image');
      //todo: check size
      $return = array();
      if($fileDetails['error'] != 0) {
        $return['error'] = $this->getContext()->getI18N()->__('ERROR_UPLOAD_FILE_TOO_LARGE', 'join');
      }else {
        $extensionList = array('jpg', 'jpeg', 'png', 'gif');
        $pathinfo =  pathinfo($fileDetails['name']);
        $extension = strtolower($pathinfo['extension']);
        if(!in_array($extension, $extensionList)) {
          $return['error'] = ___("ERROR_UPLOAD_INVALID_EXTENSION", 'join');
        }else {
          $large = new sfThumbnail(800, 600);
          $med = new sfThumbnail(400, 300);
          $small = new sfThumbnail(90, 70);

        }
        $small->loadFile($fileDetails['tmp_name']);
        $med->loadFile($fileDetails['tmp_name']);
        $large->loadFile($fileDetails['tmp_name']);

        $basefilename = md5($fileDetails['tmp_name']).'.jpg';
        $thumb_filename = '90x70_'.$basefilename;
        $med_filename = '400x300_'.$basefilename;
        $big_filename = '800x600_'.$basefilename;

        $small->save($fullUploadDir.$thumb_filename);
        $med->save($fullUploadDir.$med_filename);
        $large->save($fullUploadDir.$big_filename);

        $return['src'] = $uploadDir.$thumb_filename;
        $return['filename'] = $basefilename;
      }

    }catch(Exception $e) {
      $return['error'] = $e->getMessage();
    }
    $this->getResponse()->setContentType('text/plain');
    echo json_encode($return);
    //on the server, display header sent warning otherwise

    ini_set('display_errors', '0');
    return sfView::NONE;
  }
  public function executeListExportcsv(sfWebRequest $request) {
    $vehicle = VehicleTable::getInstance()->findAll();
    $this->varr = array();

    $i = 0;
    foreach($vehicle as $v) {
      $this->varr[$i] = array(
              'bodystyle'=>$v->getBodyStyle()->getName(),
              'tansmission'=>$v->getTransmissionName(),
              'price'=>$v->getPrice(),
              'year'=>$v->getYear(),
              'mileage'=>$v->getMileage(),
              'color'=>$v->getExteriorColor(),
              'fuel'=>$v->getFuelName(),
              'name'=>$v->getName(),
              'doors'=>$v->getDoors(),
              'stock ID'=>$v->getStockId(),
              'engine'=>$v->getEngine(),
              'description'=>$v->getDescription(),
              'make'=>$v->getMake()->getName(),
              'model'=>$v->getModel()->getName());
      $pictures = $v->getPictures();
      $j = 1;
      foreach($pictures as $p) {
        $tmp['picture_'.$i]=sfConfig::get('app_image_path').$p->getFilename();
        $j++;
      }
      $this->varr[$i] = array_merge($this->varr[$i], $tmp);
      $i++;
    }

    $enclosure ='"';
    $delim=',';
    $newline = "\n";
    $out = '';
    foreach ( $this->varr as $row) {
      $key = array_keys($row);
      foreach ($row as $item) {
        $out .= $enclosure.str_replace($enclosure, $enclosure.$enclosure, $item).$enclosure.$delim;
      }
      $out = substr($out, 0, -1);
      $out = rtrim($out);
      $out .= $newline;
    }

    $response = $this->getResponse();
    $response->setHttpHeader('content-type','text/msexcel');
    $response->setHttpHeader('content-disposition','attachment; filename=\"mvm-stock-list.csv\"');
    $response->setContent($out);
    $response->send();
    die();

  }
  public function listImportcsv(sfWebRequest $request) {

  }
}
